package com.mdd.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author XYueong
 * @date 2023-12-01
 * @description: 邮件工具
 */
@Slf4j
public class MailUtil {


    public static void sendMail(String recipientEmail,String mailTitle,String mailContent) {
        // 发件人邮箱和密码
        String senderEmail = "xyueong@outlook.com";
        String password = "iscujxktehxgkeel";


        // 设置邮件属性
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp-mail.outlook.com");
        properties.put("mail.smtp.port", "587");

        // 创建 Session 对象
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, password);
            }
        });

        try {
            // 创建 MimeMessage 对象
            Message message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(senderEmail));
            // 设置收件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
            // 设置邮件主题
            message.setSubject(mailTitle);

            // 设置 HTML 内容
            message.setContent(mailContent, "text/html;charset=UTF-8");

            // 发送邮件
            Transport.send(message);

        log.info("邮件发送成功");
        } catch (MessagingException e) {
            log.error("邮件发送失败");
        }
    }

}
